#include <iostream>
#include <functional>
#include <math.h>
using std::cout;
using std::endl;
using std::bind;
using std::function;

//使用Function + bind 实现与多态相同的功能
class figure{
public:
    using Func1 = function<double()>;
    using Func2 = function<void()>;

    void set_f1(Func1 && f){ 
        _f1 = std::move(f);
    }
    void set_f2(Func2 && f){
        _f2 = std::move(f);
    }

    double execute1(){
        if(_f1){
            return _f1();
        }
        return 0.0;
    }

    void execute2(){
        if(_f2){
            _f2();
        }
    }
private:
    //一开始 _f1,_f2会调用std::function的默认构造函数，被初始化为“空”状态
    Func1 _f1;
    Func2 _f2;
};


class Triangle{
public:
    Triangle(double a=0, double b=0, double c=0)
    :_a(a),_b(b),_c(c)
    {
    }

    double area(){
        double temp = (_a+_b+_c)/2;
        return sqrt(temp * (temp - _a)*(temp - _b) * (temp - _c));
    }

    void print(int a){
        cout << "Triangle" << a <<endl;
    } 
private:
    double _a,_b,_c;
};

void test(){
    Triangle t(2,2,3);

    figure fig;
    fig.set_f1(bind(&Triangle::area,&t));
    cout << fig.execute1() << endl;
    fig.set_f2(bind(&Triangle::print,&t,1));
    fig.execute2();
}

void test2(){
    Triangle t(2,2,3);
    figure fig;
    auto f = bind(&Triangle::area,&t);
    fig.set_f1(f);
    cout << fig.execute1() << endl;
}

int main()
{


    test ();
    //test2();
    return 0;
}

